<template>
  <!-- 关键字搜索 -->
  <ve-search-bar
    :showBorder="true"
    class="search-bar"
    placeholder="订单号/车牌号/承租人/承租人手机号"
    v-model="queryParam.keywords"
    @confirm="onKeywordSearch"
    ref="vesearchbar"
  />
  <!-- 订单状态 -->
  <ve-tabs
    class="order-tabs"
    :style="stickyStyle"
    :actived="selectOrderStatusIndex"
    :list="orderStatusList"
    @change="onOrderStatusChange"
  />
  <!-- 订单排序&标签 -->
  <view class="filter-tabs" :style="stickyStyle" :id="`filter-tabs-wrapper-${type}`">
    <!-- 订单排序 -->
    <view class="sort-result-show" @click="sortClickFn">
      <view class="sort-result-show-text">{{ activedSort.s_label }}</view>
      <ve-icon v-if="sortPopupVisible" class="sort-result-show-arrow" name="icon-triangle-up" width="24" height="24"></ve-icon>
      <ve-icon v-else class="sort-result-show-arrow" name="icon-triangle-down" width="24" height="24"></ve-icon>
      <view class="sort-result-show-split-line"></view>
    </view>
    <!-- 订单标签 -->
    <view class="tabs-labels-wrapper">
      <OrderStatusTags ref="orderStatusTagsRef" :modelValue="checkedLabelIndexList" :list="currLabelList" @change="onLabelChange" />
    </view>
    <!-- 订单标签更多按钮 -->
    <view class="tabs-labels-more" @tap="onShowLabelCheckPopup">
      <view class="tabs-labels-more-shadow"></view>
      <view class="tabs-labels-more-content">
        <ve-icon name="filter-more" width="64" height="64" />
        <view class="badge" v-if="checkedLabelIndexList.length > 0">{{ checkedLabelIndexList.length }}</view>
      </view>
    </view>
  </view>
  <!-- 订单排序悬浮框 -->
  <ve-popup v-model="sortPopupVisible" mode="top" class="sort-popup" :offset="sortPopupOffsetTop" @close="sortPopupVisible = false">
    <view class="sort-type-list">
      <view
        class="sort-item"
        v-for="sortItem in sortList"
        :key="sortItem.value"
        :class="{ 'sort-item-active': sortItem.value == activedSort.value }"
        @tap="onSortChange(sortItem)"
      >
        {{ sortItem.label }}
        <view class="sort-item-choice">
          <ve-icon name="sort-choice" width="28" height="28"></ve-icon>
        </view>
      </view>
    </view>
  </ve-popup>
  <!-- 订单标签悬浮框 -->
  <MoreTagsModal
    v-model="moreLabelFilterVisible"
    :list="currLabelList"
    :checkedList="checkedLabelIndexList"
    @close="closeLabelModal"
    @confirm="confirmLabelModal"
  />
</template>

<script setup>
  import { ref, inject, computed, onMounted, nextTick } from 'vue'
  import OrderStatusTags from './order-status-tags.vue'
  import MoreTagsModal from './more-tags-modal.vue'
  import sOrderConfig from '../../short-order/components/order-item/orderTabsConfig.js'
  import lOrderConfig from '../../long-order/components/order-item/orderTabsConfig.js'
  import { pxToRpx, cloneDeep } from '@/utils'
  import { userStore } from '@/stores'
  const userInfoStore = userStore()
  const props = defineProps({
    type: String,
  })
  // queryParam 上层组件传递
  const queryParam = inject('queryParam')
  // emit 传递事件
  const emit = defineEmits(['change'])
  // 短长租 queryParam 对应不同的 key
  const propsKey = computed(() => {
    if (props.type == 'short-order') {
      return {
        orderStatus: 'orderStatus',
        orderLabels: 'orderLabels',
      }
    } else {
      return {
        orderStatus: 'status',
        orderLabels: 'orderLableList',
      }
    }
  })

  // 订单状态列表
  const orderStatusList = ref([])
  // 是否开启核实订单
  const isVerifyOrder = userInfoStore.enterpriseDetail?.config?.orderLabelEnabledList?.includes(2)
  const verifyOrder = ['待审核', '已审核']

  if (props.type == 'short-order') {
    let { getList, tabsConfigList } = sOrderConfig
    let config = cloneDeep(tabsConfigList)

    // 是否开启核实订单
    if (isVerifyOrder) {
      config.forEach((item) => {
        getList(verifyOrder)
        item.qucikLabels.splice(-1, 0, ...getList(verifyOrder))
      })
    }

    let userShortRentChannels = userInfoStore.enterpriseDetail?.userShortRentChannels
    if (userShortRentChannels?.length > 0) {
      // 根据配置处理 小程序、携程、飞猪、哈罗、悟空、铁行、飞租
      let alias = {
        // 0: '小程序',
        2: '悟空',
        3: '哈啰',
        4: '携程',
        5: '飞猪',
        6: '滴滴',
        7: '铁行',
        8: '飞租',
      }
      let addList = []
      userShortRentChannels.forEach((channelId) => {
        if (alias[channelId]) {
          addList.push(alias[channelId])
        }
      })
      config.forEach((item) => {
        getList(addList)
        item.qucikLabels = item.qucikLabels.concat(getList(addList))
      })
    }

    console.log('short config', config)

    orderStatusList.value = config
  } else {
    let { getList, tabsConfigList } = lOrderConfig
    let config = cloneDeep(tabsConfigList)

    // 是否开启核实订单
    if (isVerifyOrder) {
      config.forEach((item) => {
        getList(verifyOrder)
        item.qucikLabels.splice(-1, 0, ...getList(verifyOrder))
      })
    }

    console.log('long config', config)

    orderStatusList.value = config
  }
  // 选中的订单状态下标
  const selectOrderStatusIndex = computed(() => {
    let index = 0
    if (queryParam[propsKey.value.orderStatus]) {
      index = orderStatusList.value.findIndex((item) => item.value == queryParam[propsKey.value.orderStatus])
    }
    return index
  })
  // 选中的订单状态对象
  const activeTab = computed(() => {
    return orderStatusList.value[selectOrderStatusIndex.value]
  })
  // 当其订单状态对应的标签列表
  const currLabelList = computed(() => {
    return activeTab.value.qucikLabels || []
  })
  // 当前选中的标签下标集合
  const checkedLabelIndexList = computed(() => {
    const list = queryParam[propsKey.value.orderLabels] || []
    let activeIndexList = []
    list.forEach((label) => {
      let index = currLabelList.value.findIndex((item) => {
        return item.name == label
      })
      activeIndexList.push(index)
    })
    return activeIndexList
  })
  // 订单状态切换函数
  const onOrderStatusChange = (index) => {
    // 更新 queryParam 中的 orderLabels
    queryParam[propsKey.value.orderLabels] = []
    // 更新 queryParam 中的 orderStatus
    queryParam[propsKey.value.orderStatus] = orderStatusList.value[index].value
    // 切换当前状态的默认排序
    onSortChange(activeTab.value.defaultSort)
    emit('change', 'orderStatus')
  }

  // 排序列表
  const sortList = computed(() => {
    return activeTab.value.sort
  })

  // 订单排序切换函数
  const activedSort = computed(() => {
    return sortList.value.find((item) => item.value == queryParam['sortField']) || activeTab.value.defaultSort
  })
  const onSortChange = (sort, isEmit = true) => {
    sortPopupVisible.value = false
    // 排序字段
    const sortField = sort.value
    // 排序规则 asc（正序） desc （倒序）
    const sortType = sort.sort
    queryParam['sortField'] = sortField
    queryParam['sortType'] = sortType
    if (isEmit) emit('change', 'orderSort')
  }
  // 标签选中函数
  const onLabelChange = (checkedList) => {
    let labelNames = []
    if (Array.isArray(checkedList)) {
      let selectLabels = currLabelList.value.filter((item, index) => {
        return checkedList.includes(index)
      })
      labelNames = selectLabels.map((item) => {
        return item.name
      })
    }
    queryParam[propsKey.value.orderLabels] = labelNames

    emit('change', 'orderLabels')
  }
  // 订单标签悬浮框
  const moreLabelFilterVisible = ref(false)
  // 开启订单标签悬浮框
  const onShowLabelCheckPopup = () => {
    moreLabelFilterVisible.value = true
    uni.hideTabBar()
  }
  // 订单标签悬浮框关闭
  const closeLabelModal = () => {
    uni.showTabBar()
  }
  // 订单标签悬浮框点击确认筛选
  const confirmLabelModal = (list) => {
    uni.showTabBar()
    onLabelChange(list)
  }
  // 查询条件 搜索
  const onKeywordSearch = () => {
    emit('change', 'orderKeywords')
  }

  // 排序相关逻辑
  const sortPopupVisible = ref(false)
  const sortClickFn = async () => {
    // 重新计算排序弹窗距离顶部距离
    await calcSortPopupOffsetTop()
    sortPopupVisible.value = !sortPopupVisible.value
  }

  // 更新 tabs 角标
  const updateTabsNum = (result = {}) => {
    orderStatusList.value.forEach((item) => {
      item.num = result[item.numProp] || 0
    })
  }
  // 更新 labels 角标
  const orderStatusTagsRef = ref(null)
  const updateLabelsnum = (result) => {
    currLabelList.value.forEach((label) => {
      label.num = result[label.numProp] || 0
    })
    nextTick(() => {
      orderStatusTagsRef.value.updateTabsRect()
    })
  }
  // 粘性定位样式
  const stickyStyle = ref({})
  // 排序弹窗距离顶部距离
  const sortPopupOffsetTop = ref(0)
  /**
   * 计算排序弹窗距离顶部距离
   */
  const calcSortPopupOffsetTop = () => {
    return new Promise((resolve, reject) => {
      // 处理 sortPopupOffsetTop
      const query = uni.createSelectorQuery().in(this)
      query
        .select(`#filter-tabs-wrapper-${props.type}`)
        .boundingClientRect((rect) => {
          let { height, top } = rect
          sortPopupOffsetTop.value = pxToRpx(height + top)
          resolve()
        })
        .exec()
    })
  }
  onMounted(() => {
    // 初始化计算排序弹窗距离顶部距离
    calcSortPopupOffsetTop()
    const statusBarHeight = uni.getSystemInfoSync().statusBarHeight
    stickyStyle.value = {
      position: 'sticky',
      top: (statusBarHeight + 44) * 2 + 'rpx',
    }
  })
  defineExpose({
    updateTabsNum,
    updateLabelsnum,
    closePopupLabel: () => (sortPopupVisible.value = false),
  })
</script>
<style lang="less" scoped>
  .filter-tabs {
    display: flex;
    height: 88rpx;
    align-items: center;
    justify-content: space-around;
    background-color: #ffffff;
    z-index: 998;
    .sort-result-show {
      width: 250rpx;
      height: 100%;
      padding: 0 14rpx 0 32rpx; //ios
      display: flex;
      align-items: center;
      .sort-result-show-text {
        height: 44rpx;
        line-height: 44rpx;
        font-size: 24rpx;
        color: #3072f6;
      }
      .sort-result-show-arrow {
        margin: 0 15rpx;
        height: 24rpx;
      }
      .sort-result-show-split-line {
        width: 2rpx;
        height: 44rpx;
        background: #dadbdd;
      }
    }
    .tabs-labels-wrapper {
      width: calc(100% - 108rpx - 250rpx);
      height: 48rpx;
    }
    .tabs-labels-more {
      width: 105rpx;
      height: 100%;
      position: relative;
      padding-top: 16rpx;
      padding-left: 14rpx;
      .tabs-labels-more-shadow {
        width: 20rpx;
        height: 100%;
        position: absolute;
        left: 0;
        top: 0;
        box-shadow: -8px 0px 8px -2px rgba(185, 200, 217, 0.31);
      }
      .tabs-labels-more-content {
        .badge {
          height: 32rpx;
          line-height: 32rpx;
          font-size: 24rpx;
          color: #3072f6;
          background: #c6dafb;
          border-radius: 50%;
          padding: 0 8rpx;
          font-weight: 600;
          position: absolute;
          top: 14rpx;
          right: 16rpx;
        }
      }
    }
  }
  /deep/ .ve-popup {
    .ve-popup-content.content-top {
      border-radius: 0 0 16rpx 16rpx;
    }
  }
  .sort-type-list {
    padding-bottom: 8rpx;
    .sort-item {
      padding: 24rpx 32rpx;
      font-size: 28rpx;
      color: #1d2129;
      position: relative;
      .sort-item-choice {
        position: absolute;
        right: 32rpx;
        top: 24rpx;
        visibility: hidden;
      }
    }
    .sort-item-active {
      font-weight: 600;
      color: #3072f6;
      .sort-item-choice {
        visibility: visible;
      }
    }
  }
  .search-bar {
    position: sticky;
    top: 0;
    z-index: 999;
  }
  .order-tabs {
    z-index: 999;
    background: #ffffff;
  }
  .sort-popup {
    /deep/ .content-top {
      border-radius: 0 0 8px 8px;
    }
  }
</style>
